package cn.edu.hqu.cst.activity3;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.ProgressBar;
import android.widget.TextView;

import androidx.appcompat.app.AppCompatActivity;


public class bn8 extends AppCompatActivity {
    private int p=0;//当前进度
    private ProgressBar pb_main_download;//进度条
    private TextView tv_main_desc;//显示文本的控件
    private MyHandler myHandler=new MyHandler();//新写的Handler类
    public class MyHandler extends Handler{
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            int code=msg.what;//接受处理码
            switch (code){
                case 1:
                    p++;
                    pb_main_download.setProgress(p);//给进度条的当前进度赋值
                    tv_main_desc.setText(p+"%");//显示当前进度为多少
                    break;
            }
        }
    }
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_bn8);
        //根据ID找到进度条
        pb_main_download=findViewById(R.id.pb_main_download);
        //根据ID找到显示文本的控件
        tv_main_desc=findViewById(R.id.tv_main_desc);
    }

    //点击Download按钮所调用的方法
    public void download(View view) {
        if(0==p){//如果当前进度为0
            new myThread().start();//开启线程
        }
    }

    public class myThread extends Thread{
        @Override
        public void run() {
            super.run();
            while(true){
                try {
                    Thread.sleep(100);//使线程休眠0.1秒
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

                if(p==100){//当前进度等于总进度时退出循环
                    p=0;
                    break;
                }

                Message msg=new Message();
                msg.what=1;
                myHandler.sendMessage(msg);//发送处理码
            }
        }
    }
}

